package com.ironmaking.Utils.token;

import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;
import java.util.Map;

/**
 * @ClassName JWTutil
 * @Description 登录生成token，传入token时先判断是否合法，再去redis中检查
 */
@Component
public class JWTutil {
    private static final String key = "qwertyuiopasdfghjklzxcvbnm12345678";

    private static final long expTime =  1000*60*60*24;

    private static final SecretKey secretKey = new SecretKeySpec(key.getBytes(), SignatureAlgorithm.HS256.getJcaName());

    public String generateToken ( Integer  uid){

        JwtBuilder jwtBuilder = Jwts.builder();

        return jwtBuilder
                //header
                .setHeaderParam("typ","jwt")
                .setHeaderParam("alg","HS256")
                //payload
                .claim("userid",uid.toString())
                .setAudience(uid.toString())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis()+expTime))
                //sign
                .signWith(secretKey)
                .compact();
    }

    public Map<String,Object> checkToken (String token){
        try {
            System.out.println("获取到的token:" + token);
            return (Map<String, Object>) Jwts.parser().setSigningKey(secretKey).parse(token).getBody();
        } catch (Exception e) {
            return  null;
        }
    }
}
